
from lib.validator import Validator
from lib.form import Form
from model.comment import CommentDao
from model.user import UserDao
from model.post import PostDao

from bson.dbref import DBRef
from flask import request
from flask_login import login_user, current_user
import time

from service import Service

class CommentService(Service):
    def __init__(self):
        self.dao = CommentDao()
        self.user_dao = UserDao()
        self.post_dao = PostDao()
    
    def get_comments(self, query={}):
        comments = []
        _comments = self.dao.find(query)
        for _comment in _comments:
            author = self.user_dao.find_one({'_id':_comment.author.id})
            
            if _comment.type == 0: # comment
                source = self.post_dao.find_one({'_id':_comment.source.id})
                comments.append({"body":_comment.body, 
                              "to":source.author.username,
                              "mode":'comment', 
                              "author":author.username,
                              "created":_comment.created})
                
            elif _comment.type == 1: # reply
                source = self.comment_dao.find_one({'_id':_comment.source.id})
                comments.append({"body":_comment.body, 
                              "to":source.author.username,
                              "mode":'reply', 
                              "author":author.username,
                              "created":_comment.created})
        return comments


    def submit_comment(self, form):
        _dict = {'body':form.body,
             'mode':form.mode,
             'created': time.time(),
             'author': DBRef('users', form.author._id)}
        
        if form.mode == 0: # comment
            source = self.post_dao.find_one({'id':form.sid})
            _dict['source'] = DBRef('posts', source._id)
        elif form.mode == 1: # reply
            source = self.comment_dao.find_one({'id':form.sid})
            _dict['source'] = DBRef('comments', source._id)
        
        self.dao.save(_dict)


class CommentValidator(Validator):
    def __init__(self):
        Validator.__init__(self)
              
        self.rules = {'body': { 
                                'required' : [None, True],
                                'minlength':[None, 1],
                                'maxlength':[None, 256]
                                }
        }

    
class CommentForm(Form):
    """ Submit user form
    """
    def __init__(self):
        """Only accept POST request
        """
        Form.__init__(self)
        self.validator = CommentValidator()
        
        if self.is_submitted():
            inputs = self.get_raw_inputs()
            self.errors = self.validator.validate(inputs)
            if self.errors == []:
                self.sid = self.request.values.get('sid')
                self.body = self.request.values.get('body')
                self.mode = self.request.values.get('mode')
                self.author = current_user
                
                
    def has_error(self):
        return self.errors != []